package moe.service;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.LogManager;

import moe.collection.CollectionScanner;
import moe.config.Configuration;
import moe.config.Constants;
import moe.server.MoeServer;

public class Console implements ActionListener, MouseListener {
	// private final static Logger log = Logger.getLogger(Console.class.getName());

	private static Console console = new Console();
	private MoeServer server;
	private CollectionScanner collectionScanner;
	private Tray tray;

	private void startup(boolean createTray) {
		try {
			LogManager.getLogManager().readConfiguration(
					ClassLoader.getSystemResourceAsStream(Constants.LOGGING_CONF_FILE));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		server = new MoeServer();
		collectionScanner = new CollectionScanner();
		if (createTray) {
			createTray();
		}
		if (Configuration.isOpenBrowser()) {
			Browser.open();
		}
		collectionScanner.listen();
		server.startup();
	}

	private void shutdown() {
		if (tray != null) {
			tray.destroy();
		}
		collectionScanner.shutdown();
		server.shutdown();
	}

	private void createTray() {
		tray = new Tray(this);
		tray.createTray();
	}

	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		if ("exit".equals(command)) {
			shutdown();
		} else if ("browse".equals(command)) {
			// for some reason, IKVM ignores setActionCommand
			Browser.open();
		}
	}

	public void mouseClicked(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON1) {
			Browser.open();
		}
	}

	public void mouseEntered(MouseEvent e) {
		// nothing to do
	}

	public void mouseExited(MouseEvent e) {
		// nothing to do
	}

	public void mousePressed(MouseEvent e) {
		// nothing to do
	}

	public void mouseReleased(MouseEvent e) {
		// nothing to do
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Set<String> params = new HashSet<String>();
		params.addAll(Arrays.asList(args));
		console.startup(params.contains("tray"));
	}
}
